<template>
  <div>
    <!-- 面包屑 -->
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card class="box-card">
      <el-button type="primary" @click="ADDlogVisible = true"
        >添加角色</el-button
      >
      <!-- 添加按钮对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="ADDlogVisible"
        @close="Rolescloes"
        width="30%"
      >
        <el-form
          :model="roleslists"
          ref="RolesRef"
          :rules="Rolesrules"
          label-width="90px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              type="text"
              v-model="roleslists.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input
              type="text"
              v-model="roleslists.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="ADDlogVisible = false">取 消</el-button>
          <el-button type="primary" @click="ADDForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色列表 -->
      <template>
        <el-table
          border
          stripe
          :data="rolesList"
          style="width: 100%;margin-top:15px"
        >
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                v-for="(item, i1) in scope.row.children"
                :key="item.id"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag @close="meboxremover(scope.row, item.id)" closable>{{
                    item.authName
                  }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <el-row
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                    v-for="(itchild, i2) in item.children"
                    :key="itchild.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        closable
                        @close="meboxremover(scope.row, itchild.id)"
                        type="success"
                        >{{ itchild.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        v-for="itchch in itchild.children"
                        :key="itchch.id"
                        @close="meboxremover(scope.row, itchch.id)"
                        closable
                        type="warning"
                        >{{ itchch.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <!-- <pre>
                    {{ scope.row }}
                  </pre
              > -->
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="Editlog(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deletelog(scope.row.id)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showSetRightDialog(scope.row)"
                >分配权限</el-button
              >
              <!-- 编辑对话框 -->
              <el-dialog
                title="提示"
                :visible.sync="EditlogVisible"
                width="30%"
                @close="EditRolescloes"
              >
                <el-form
                  :model="editRolesForm"
                  ref="EditRolesRef"
                  :rules="rulesname"
                  label-width="90px"
                  class="demo-ruleForm"
                >
                  <el-form-item label="角色名称" prop="roleName">
                    <el-input
                      type="text"
                      v-model="editRolesForm.roleName"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="角色描述" prop="roleDesc">
                    <el-input
                      type="text"
                      v-model="editRolesForm.roleDesc"
                    ></el-input>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="EditlogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="EditForm">确 定</el-button>
                </span>
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <!-- 分配权限对话框 -->

    <el-dialog
      title="分配权限"
      :visible.sync="fplogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <!-- 分配权限内容 -->
      <el-tree
        show-checkbox
        default-expand-all
        :default-checked-keys="defKeys"
        node-key="id"
        :data="fpqxdata"
        :props="treeProps"
        ref="treeref"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="fplogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 定义一个数组接收数据
      rolesList: [],
      // 添加按钮显示与隐藏
      ADDlogVisible: false,
      // 定义 获取用户输入的数值
      roleslists: {
        roleName: '',
        roleDesc: ''
      },
      // 验证规则
      Rolesrules: {
        roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }]
      },
      rulesname: {
        roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }]
      },
      // 编辑角色信息对话框
      EditlogVisible: false,
      editRolesForm: {},
      // 删除对话框
      removerVisible: false,
      // 分配权限对话框
      fplogVisible: false,
      // 分配权限数据
      fpqxdata: [],
      // 权限列表
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值
      defKeys: [],
      roleId: []
    }
  },
  created() {
    // 获取数据信息
    this.getRolesList()
  },
  methods: {
    // 获取信息
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      } else {
        // console.log(res.data)
        this.rolesList = res.data
      }
    },
    // 添加角色
    ADDForm() {
      this.$refs.RolesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.roleslists)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        } else {
          this.$message.success('添加用户成功')
          this.getRolesList()
          this.ADDlogVisible = false
        }
        // console.log(res.data)
      })
    },
    // 重置添加对话框
    Rolescloes() {
      this.$refs.RolesRef.resetFields()
    },
    // 重置编辑对话框
    EditRolescloes() {
      this.$refs.EditRolesRef.resetFields()
    },
    // 打开编辑对话框
    async Editlog(rolesinfo) {
      // console.log(rolesinfo)
      const { data: res } = await this.$http.get('roles/' + rolesinfo)
      if (res.meta.status !== 200) {
        return this.$message.error('错误' + res.meta.status)
      }
      this.editRolesForm = res.data
      // console.log(this.editRolesForm)
      this.EditlogVisible = true
    },
    // 编辑角色
    EditForm() {
      this.$refs.EditRolesRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRolesForm.roleId,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          }
        )
        console.log(res.data)
        if (res.meta.status !== 200) {
          this.$message.error('编辑角色失败')
        } else {
          this.$message.success('编辑角色成功')
          this.getRolesList()
          this.EditlogVisible = false
        }
      })
    },
    // 删除角色
    async deletelog(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色，是否继续？',
        '删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消删除',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('已取消删除！')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      } else {
        this.$message.success('删除成功！')
        this.getRolesList()
      }
    },
    // 展示分配权限的数据
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('请求权列表失败')
      } else {
        // this.$message.success('请求成功！')
        // console.log(res.data)
        this.fpqxdata = res.data
        this.fplogVisible = true
        // 调用递归函数 显示三级节点id
        this.getLeafKeys(role, this.defKeys)
      }
    },
    // 递归函数，获取角色下所有三级权限的id，并保存到 defkeys 数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 清空获取id的数组
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 勾选权限
    async allRights() {
      const keys = [
        // eslint-disable-next-line dot-location
        ...this.$refs.treeref.getCheckedKeys(),
        // eslint-disable-next-line dot-location
        ...this.$refs.treeref.getHalfCheckedKeys()
      ]
      // console.log(keys)
      // 拼接字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败！')
      } else {
        this.$message.success('更新权限成功！')
        this.getRolesList()
        this.fplogVisible = false
      }
    },
    async meboxremover(rolid, id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('你已经取消了删除！')
      }
      const { data: res } = await this.$http.delete(
        `roles/${rolid.id}/rights/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      } else {
        // this.$message.success('删除成功！')
        // this.getRolesList()
        rolid.children = res.data
      }
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
